package com.canbot.u05.activity.vipguide;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.bean.PersonData2;
import com.canbot.u05.glide.GlideApp;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by cwf on 2017/5/25.
 * 认识贵宾头像选择页面
 */

public class KnowVipActivity extends BaseActivityNoTitle implements View.OnClickListener{

        private RecyclerView recyclerViewFace;

        private int selectedIndex = -1;

        private List<PersonData2> personDataList = new ArrayList<>();

        private KnowVipGridViewAdapter vipFaceAdapter;

        private Dialog dialogLoading;

        private static final String TAG = "KnowVipActivity";


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_konw_vip);
                setViews();

        }

        @Override
        protected void onResume() {
                super.onResume();
                getData();
                playSound();
        }

        private void setViews() {
                findViewById(R.id.imageView_back).setOnClickListener(this);
                findViewById(R.id.ok_btn).setOnClickListener(this);
                findViewById(R.id.face_regist).setOnClickListener(this);

                recyclerViewFace = (RecyclerView) findViewById(R.id.gv_vipface);
                recyclerViewFace.setLayoutManager(new GridLayoutManager(KnowVipActivity.this, 5));  //网格布局，每行为3
                recyclerViewFace.addItemDecoration(new GridSpacingItemDecoration(5, 20, false));
                vipFaceAdapter = new KnowVipGridViewAdapter(KnowVipActivity.this);
                recyclerViewFace.setAdapter(vipFaceAdapter);
        }

        private void playSound() {
                String[] voices = {"u05_gbgl_001.wav", "u05_gbgl_002.wav", "u05_gbgl_003.wav","u05_gbgl_004.wav"};
                int index = (int) (Math.random() * voices.length);

                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.VIP_GUIDE_DIR + voices[index]);
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "27");
                if (index == 0) {
                        MsgSendUtils.sendStringMsg(MsgType.ACTION, "14007");
                }
                else if (index == 1) {
                        MsgSendUtils.sendStringMsg(MsgType.ACTION, "14010");
                }
                else {
                        MsgSendUtils.sendStringMsg(MsgType.ACTION, "14001");
                }
        }

        private void getData() {

                Logger.e("KnowVipActivity", "getData");

                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                HashMap<String, Object> paramsMap = new HashMap<String, Object>();
                paramsMap.put("noVip", 2);//id
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 +
                        ":7755/" + "getfacerecginfo", paramsMap, new OkHttpUtils.OkHttpCallBack() {

                        @Override
                        public void onSuccess(String result) {

                                cancelDialog();
                                Logger.e(TAG, "result:" + result);

                                List<PersonData2> personDatas = JSON.parseArray(result, PersonData2.class);
                                Logger.e(TAG, "personDatas:" + personDatas.size());

                                if (personDatas.size() == 0) {
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        startActivity(new Intent(KnowVipActivity.this, VipNoFaceActivity.class));
                                                }
                                        });

                                }
                                else {
                                        Logger.e("KnowVipActivity", "分组内所有数据==" + personDataList.toString());
                                        personDataList.clear();
                                        personDataList.addAll(personDatas);
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        vipFaceAdapter.notifyDataSetChanged();
                                                }
                                        });

                                }

                        }


                        @Override
                        public void onFailure() {
                                Logger.e("KnowVipActivity", "onFailure" + "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/");
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                cancelDialog();
                                                ToastTools.newInstance(KnowVipActivity.this).showText(getString(R.string.network_request_failed));
                                        }
                                });
                        }
                });

        }


        @Override
        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.ok_btn:
                                if (selectedIndex == -1) {

                                        ToastTools.newInstance(KnowVipActivity.this).showText(getString(R.string.no_chosen_guests));

                                }
                                else {
                                        startActivity(new Intent(KnowVipActivity.this, SetVipNameActivity.class)
                                                .putExtra("identification", personDataList.get(selectedIndex).getIdentification())
                                                .putExtra("vipname", personDataList.get(selectedIndex).getName())
                                                .putExtra("facepath", personDataList.get(selectedIndex).getPath())
                                                .putExtra("isSetting","isSetting"));
                                }

                                break;
                        case R.id.imageView_back:
                                finish();
                                break;
                        case R.id.face_regist:
                                Intent intent = new Intent();
                                intent.setClassName("com.unisrobot.faceregcognize", "com.unisrobot.faceregcognize.activity.FaceRegRegisterActivity");
                                if (intent != null) {
                                        startActivity(intent);
                                }
                                break;
                        default:
                                break;
                }
        }

        @Override
        protected void onPause() {
                super.onPause();
                cancelDialog();
                MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop_sound");
        }

        /**
         * 取消加载的Dialog
         */
        private void cancelDialog() {
                if (dialogLoading != null) {
                        if (dialogLoading.isShowing()) {
                                dialogLoading.cancel();
                        }
                }
        }

        class KnowVipGridViewAdapter extends RecyclerView.Adapter<KnowVipGridViewAdapter.MyViewHolder> {

                LayoutInflater inflater;

                Context mContext;

                public KnowVipGridViewAdapter(Context mContext) {
                        this.mContext = mContext;
                        inflater = LayoutInflater.from(mContext);
                }

                @Override
                public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.gridview_vipguide_vipface, parent,false);
                        return new MyViewHolder(view);
                }

                @Override
                public void onBindViewHolder(@NonNull MyViewHolder holder, final int position) {


                        PersonData2 face =  personDataList.get(position);
                        if (position == selectedIndex) {
                                holder.ivvipbg.setVisibility(View.VISIBLE);
                        }
                        else {
                                holder.ivvipbg.setVisibility(View.INVISIBLE);
                        }
                        GlideApp.with(mContext).clear(holder.ivvipavatar);
                        GlideApp.with(mContext).asDrawable()
                                .load(IpMsgConst.HTTP_URL_CHEST  + "/temp/faces/" + face.getPath())
                                .thumbnail(0.1f)
                                .diskCacheStrategy(DiskCacheStrategy.ALL)//缓存策略
                                .skipMemoryCache(false)
                                .placeholder(R.drawable.sales_banner01)//占位图
                                .error(R.drawable.ic_picture_loadfailed)
                                .into(holder.ivvipavatar);
                        holder.textView.setText(face.getPath());
                        holder.ivvipavatar.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                        selectedIndex = position;
                                        vipFaceAdapter.notifyDataSetChanged();
                                }
                        });

                }

                @Override
                public long getItemId(int i) {
                        return i;
                }

                @Override
                public int getItemCount() {
                        if (personDataList == null) {
                                return 0;
                        }
                        return personDataList.size();

                }


                public class MyViewHolder extends RecyclerView.ViewHolder {

                        private ImageView ivvipavatar;

                        private ImageView ivvipbg;

                        private TextView textView;

                        public MyViewHolder(View view) {
                                super(view);
                                ivvipavatar = (ImageView) view.findViewById(R.id.iv_vip_avatar);
                                ivvipbg = (ImageView) view.findViewById(R.id.iv_vip_bg);
                                textView = (TextView) view.findViewById(R.id.tv);
                        }
                }
        }

}
